<template>
  <div class="implementation-tasks-container">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <span>实施任务管理</span>
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新增任务
          </el-button>
        </div>
      </template>

      <!-- 筛选器 -->
      <div class="filter-box">
        <el-radio-group v-model="filterStatus" @change="handleFilterChange">
          <el-radio-button value="all">全部({{ statistics.total }})</el-radio-button>
          <el-radio-button value="todo">待办({{ statistics.todo }})</el-radio-button>
          <el-radio-button value="inprogress">进行中({{ statistics.inprogress }})</el-radio-button>
          <el-radio-button value="completed">已完成({{ statistics.completed }})</el-radio-button>
        </el-radio-group>
      </div>

      <!-- 任务看板 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-card shadow="hover" class="task-column">
            <template #header>
              <div class="column-header">
                <el-text type="info">📋 待办任务</el-text>
                <el-tag size="small">{{ allTodoTasks.length }}</el-tag>
              </div>
            </template>
            <div 
              class="task-list drop-zone"
              :class="{ 'drag-over': dragOverStatus === 'todo' }"
              @dragover="handleDragOver($event, 'todo')"
              @dragleave="handleDragLeave"
              @drop="handleDrop($event, 'todo')"
            >
              <el-card 
                v-for="task in todoTasks" 
                :key="task.id"
                shadow="hover"
                class="task-card"
                draggable="true"
                @dragstart="handleDragStart($event, task)"
                @dragend="handleDragEnd"
                @click.stop="handleView(task)"
              >
                <div class="task-title">{{ task.title }}</div>
                <div class="task-info">
                  <el-tag size="small" type="info">{{ task.project }}</el-tag>
                  <el-text size="small" type="info">{{ task.assignee }}</el-text>
                </div>
                <div class="task-footer">
                  <el-text size="small">{{ task.dueDate }}</el-text>
                  <el-tag size="small" :type="getPriorityType(task.priority)">
                    {{ getPriorityText(task.priority) }}
                  </el-tag>
                </div>
              </el-card>
              <div v-if="todoTasks.length === 0" class="empty-placeholder">
                拖动任务到此处
              </div>
            </div>
            <div v-if="allTodoTasks.length > pagination.todo.size" class="column-pagination">
              <el-pagination
                small
                :current-page="pagination.todo.page"
                :page-size="pagination.todo.size"
                :total="allTodoTasks.length"
                layout="prev, pager, next"
                @current-change="(page) => handlePageChange('todo', page)"
              />
            </div>
          </el-card>
        </el-col>

        <el-col :span="8">
          <el-card shadow="hover" class="task-column">
            <template #header>
              <div class="column-header">
                <el-text type="primary">🔄 进行中</el-text>
                <el-tag size="small" type="primary">{{ allInprogressTasks.length }}</el-tag>
              </div>
            </template>
            <div 
              class="task-list drop-zone"
              :class="{ 'drag-over': dragOverStatus === 'inprogress' }"
              @dragover="handleDragOver($event, 'inprogress')"
              @dragleave="handleDragLeave"
              @drop="handleDrop($event, 'inprogress')"
            >
              <el-card 
                v-for="task in inprogressTasks" 
                :key="task.id"
                shadow="hover"
                class="task-card"
                draggable="true"
                @dragstart="handleDragStart($event, task)"
                @dragend="handleDragEnd"
                @click.stop="handleView(task)"
              >
                <div class="task-title">{{ task.title }}</div>
                <div class="task-info">
                  <el-tag size="small" type="primary">{{ task.project }}</el-tag>
                  <el-text size="small" type="info">{{ task.assignee }}</el-text>
                </div>
                <el-progress :percentage="task.progress" :status="task.progress === 100 ? 'success' : ''" />
                <div class="task-footer">
                  <el-text size="small">{{ task.dueDate }}</el-text>
                  <el-tag size="small" :type="getPriorityType(task.priority)">
                    {{ getPriorityText(task.priority) }}
                  </el-tag>
                </div>
              </el-card>
              <div v-if="inprogressTasks.length === 0" class="empty-placeholder">
                拖动任务到此处
              </div>
            </div>
            <div v-if="allInprogressTasks.length > pagination.inprogress.size" class="column-pagination">
              <el-pagination
                small
                :current-page="pagination.inprogress.page"
                :page-size="pagination.inprogress.size"
                :total="allInprogressTasks.length"
                layout="prev, pager, next"
                @current-change="(page) => handlePageChange('inprogress', page)"
              />
            </div>
          </el-card>
        </el-col>

        <el-col :span="8">
          <el-card shadow="hover" class="task-column">
            <template #header>
              <div class="column-header">
                <el-text type="success">✅ 已完成</el-text>
                <el-tag size="small" type="success">{{ allCompletedTasks.length }}</el-tag>
              </div>
            </template>
            <div 
              class="task-list drop-zone"
              :class="{ 'drag-over': dragOverStatus === 'completed' }"
              @dragover="handleDragOver($event, 'completed')"
              @dragleave="handleDragLeave"
              @drop="handleDrop($event, 'completed')"
            >
              <el-card 
                v-for="task in completedTasks" 
                :key="task.id"
                shadow="hover"
                class="task-card completed"
                draggable="true"
                @dragstart="handleDragStart($event, task)"
                @dragend="handleDragEnd"
                @click.stop="handleView(task)"
              >
                <div class="task-title">{{ task.title }}</div>
                <div class="task-info">
                  <el-tag size="small" type="success">{{ task.project }}</el-tag>
                  <el-text size="small" type="info">{{ task.assignee }}</el-text>
                </div>
                <div class="task-footer">
                  <el-text size="small" type="success">{{ task.completeDate }}</el-text>
                  <el-icon color="#67C23A"><CircleCheckFilled /></el-icon>
                </div>
              </el-card>
              <div v-if="completedTasks.length === 0" class="empty-placeholder">
                拖动任务到此处
              </div>
            </div>
            <div v-if="allCompletedTasks.length > pagination.completed.size" class="column-pagination">
              <el-pagination
                small
                :current-page="pagination.completed.page"
                :page-size="pagination.completed.size"
                :total="allCompletedTasks.length"
                layout="prev, pager, next"
                @current-change="(page) => handlePageChange('completed', page)"
              />
            </div>
          </el-card>
        </el-col>
      </el-row>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="700px">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="任务标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入任务标题" />
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="所属项目" prop="project">
              <el-select v-model="form.project" placeholder="请选择项目" style="width: 100%">
                <el-option label="XX集团ERP实施项目" value="XX集团ERP实施项目" />
                <el-option label="YY公司财务系统上线" value="YY公司财务系统上线" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="负责人" prop="assignee">
              <el-select v-model="form.assignee" placeholder="请选择负责人" style="width: 100%">
                <el-option label="张伟" value="张伟" />
                <el-option label="李娜" value="李娜" />
                <el-option label="王强" value="王强" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="优先级" prop="priority">
              <el-select v-model="form.priority" placeholder="请选择优先级" style="width: 100%">
                <el-option label="低" value="low" />
                <el-option label="中" value="medium" />
                <el-option label="高" value="high" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="截止日期" prop="dueDate">
              <el-date-picker v-model="form.dueDate" type="date" style="width: 100%" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="任务描述">
          <el-input v-model="form.description" type="textarea" :rows="4" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus, CircleCheckFilled } from '@element-plus/icons-vue'

const filterStatus = ref('all')
const dialogVisible = ref(false)
const dialogTitle = ref('新增任务')
const formRef = ref()

const statistics = reactive({
  total: 0,
  todo: 0,
  inprogress: 0,
  completed: 0
})

const allTasks = ref([])

// 拖拽相关状态
const draggedTask = ref(null)
const dragOverStatus = ref(null)

// 分页状态
const pagination = reactive({
  todo: { page: 1, size: 5 },
  inprogress: { page: 1, size: 5 },
  completed: { page: 1, size: 5 }
})

const form = reactive({
  title: '',
  project: '',
  assignee: '',
  priority: 'medium',
  dueDate: '',
  description: ''
})

const rules = {
  title: [{ required: true, message: '请输入任务标题', trigger: 'blur' }],
  project: [{ required: true, message: '请选择项目', trigger: 'change' }],
  assignee: [{ required: true, message: '请选择负责人', trigger: 'change' }]
}

// 获取所有任务（按状态）
const allTodoTasks = computed(() => allTasks.value.filter(t => t.status === 'todo'))
const allInprogressTasks = computed(() => allTasks.value.filter(t => t.status === 'inprogress'))
const allCompletedTasks = computed(() => allTasks.value.filter(t => t.status === 'completed'))

// 获取分页后的任务
const todoTasks = computed(() => {
  const start = (pagination.todo.page - 1) * pagination.todo.size
  const end = start + pagination.todo.size
  return allTodoTasks.value.slice(start, end)
})

const inprogressTasks = computed(() => {
  const start = (pagination.inprogress.page - 1) * pagination.inprogress.size
  const end = start + pagination.inprogress.size
  return allInprogressTasks.value.slice(start, end)
})

const completedTasks = computed(() => {
  const start = (pagination.completed.page - 1) * pagination.completed.size
  const end = start + pagination.completed.size
  return allCompletedTasks.value.slice(start, end)
})

const getPriorityType = (priority) => {
  const map = { low: 'info', medium: 'warning', high: 'danger' }
  return map[priority] || ''
}

const getPriorityText = (priority) => {
  const map = { low: '低', medium: '中', high: '高' }
  return map[priority] || priority
}

const getStatusText = (status) => {
  const map = { todo: '待办任务', inprogress: '进行中', completed: '已完成' }
  return map[status] || status
}

// 拖拽事件处理
const handleDragStart = (e, task) => {
  draggedTask.value = task
  e.dataTransfer.effectAllowed = 'move'
  e.target.style.opacity = '0.5'
}

const handleDragEnd = (e) => {
  e.target.style.opacity = '1'
  draggedTask.value = null
  dragOverStatus.value = null
}

const handleDragOver = (e, status) => {
  e.preventDefault()
  e.dataTransfer.dropEffect = 'move'
  dragOverStatus.value = status
}

const handleDragLeave = () => {
  dragOverStatus.value = null
}

const handleDrop = (e, newStatus) => {
  e.preventDefault()
  dragOverStatus.value = null
  
  if (!draggedTask.value) return
  
  const task = draggedTask.value
  const oldStatus = task.status
  
  // 如果状态相同，不做处理
  if (oldStatus === newStatus) {
    return
  }
  
  // 更新任务状态
  const taskIndex = allTasks.value.findIndex(t => t.id === task.id)
  if (taskIndex !== -1) {
    allTasks.value[taskIndex].status = newStatus
    
    // 如果移到已完成，添加完成日期
    if (newStatus === 'completed') {
      const today = new Date().toISOString().split('T')[0]
      allTasks.value[taskIndex].completeDate = today
    }
    
    // 如果从已完成移出，删除完成日期
    if (oldStatus === 'completed') {
      delete allTasks.value[taskIndex].completeDate
    }
    
    // 如果移到进行中且没有进度，设置默认进度
    if (newStatus === 'inprogress' && !allTasks.value[taskIndex].progress) {
      allTasks.value[taskIndex].progress = 0
    }
    
    // 更新统计数据
    updateStatistics()
    
    // 检查原状态列是否需要调整页码（如果当前页为空）
    const statusMap = {
      'todo': allTodoTasks,
      'inprogress': allInprogressTasks,
      'completed': allCompletedTasks
    }
    const tasksInOldStatus = statusMap[oldStatus].value
    const maxPage = Math.ceil(tasksInOldStatus.length / pagination[oldStatus].size) || 1
    if (pagination[oldStatus].page > maxPage) {
      pagination[oldStatus].page = maxPage
    }
    
    ElMessage.success(`任务已从"${getStatusText(oldStatus)}"移动到"${getStatusText(newStatus)}"`)
  }
}

const handleFilterChange = () => {
  ElMessage.info('筛选：' + filterStatus.value)
}

const handleAdd = () => {
  dialogTitle.value = '新增任务'
  dialogVisible.value = true
}

const handleView = (task) => {
  ElMessage.info('查看任务：' + task.title)
}

const handleSubmit = () => {
  formRef.value?.validate((valid) => {
    if (valid) {
      ElMessage.success('操作成功')
      dialogVisible.value = false
    }
  })
}

const updateStatistics = () => {
  statistics.total = allTasks.value.length
  statistics.todo = allTodoTasks.value.length
  statistics.inprogress = allInprogressTasks.value.length
  statistics.completed = allCompletedTasks.value.length
}

// 分页处理
const handlePageChange = (status, page) => {
  pagination[status].page = page
}

// 生成模拟数据
const generateMockData = () => {
  const taskTitles = [
    '需求调研', '系统配置', '数据迁移', '用户培训', '系统测试', 
    '上线准备', '文档编写', '功能开发', '接口对接', '报表设计',
    '权限配置', '流程梳理', '二次开发', '系统集成', '数据清洗',
    '性能优化', '安全加固', '备份方案', '应急演练', '验收准备'
  ]
  const projects = ['XX集团ERP实施项目', 'YY公司财务系统上线', 'ZZ制造业ERP项目', 'AA科技CRM部署', 'BB商贸WMS系统']
  const assignees = ['张伟', '李娜', '王强', '赵敏', '刘芳', '陈明']
  const priorities = ['low', 'medium', 'high']
  const statuses = ['todo', 'inprogress', 'completed']
  
  const tasks = []
  
  // 生成待办任务 8条
  for (let i = 0; i < 8; i++) {
    tasks.push({
      id: tasks.length + 1,
      title: taskTitles[Math.floor(Math.random() * taskTitles.length)],
      project: projects[Math.floor(Math.random() * projects.length)],
      assignee: assignees[Math.floor(Math.random() * assignees.length)],
      priority: priorities[Math.floor(Math.random() * priorities.length)],
      dueDate: `2024-${String(Math.floor(Math.random() * 2) + 10).padStart(2, '0')}-${String(Math.floor(Math.random() * 28) + 1).padStart(2, '0')}`,
      status: 'todo'
    })
  }
  
  // 生成进行中任务 12条
  for (let i = 0; i < 12; i++) {
    tasks.push({
      id: tasks.length + 1,
      title: taskTitles[Math.floor(Math.random() * taskTitles.length)],
      project: projects[Math.floor(Math.random() * projects.length)],
      assignee: assignees[Math.floor(Math.random() * assignees.length)],
      priority: priorities[Math.floor(Math.random() * priorities.length)],
      progress: Math.floor(Math.random() * 90) + 10,
      dueDate: `2024-${String(Math.floor(Math.random() * 2) + 10).padStart(2, '0')}-${String(Math.floor(Math.random() * 28) + 1).padStart(2, '0')}`,
      status: 'inprogress'
    })
  }
  
  // 生成已完成任务 15条
  for (let i = 0; i < 15; i++) {
    tasks.push({
      id: tasks.length + 1,
      title: taskTitles[Math.floor(Math.random() * taskTitles.length)],
      project: projects[Math.floor(Math.random() * projects.length)],
      assignee: assignees[Math.floor(Math.random() * assignees.length)],
      priority: priorities[Math.floor(Math.random() * priorities.length)],
      completeDate: `2024-${String(Math.floor(Math.random() * 2) + 8).padStart(2, '0')}-${String(Math.floor(Math.random() * 28) + 1).padStart(2, '0')}`,
      status: 'completed'
    })
  }
  
  return tasks
}

onMounted(() => {
  allTasks.value = generateMockData()
  updateStatistics()
})
</script>

<style scoped>
.implementation-tasks-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-box {
  margin-bottom: 20px;
}

.task-column {
  min-height: 600px;
}

.column-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.task-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
  min-height: 400px;
}

.drop-zone {
  position: relative;
  padding: 10px;
  border-radius: 8px;
  transition: all 0.3s;
}

.drop-zone.drag-over {
  background-color: rgba(64, 158, 255, 0.1);
  border: 2px dashed #409eff;
}

.empty-placeholder {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100px;
  color: #999;
  font-size: 14px;
  border: 2px dashed #e4e7ed;
  border-radius: 8px;
  transition: all 0.3s;
}

.drag-over .empty-placeholder {
  border-color: #409eff;
  color: #409eff;
}

.task-card {
  cursor: move;
  transition: all 0.3s;
  user-select: none;
}

.task-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.task-card.completed {
  opacity: 0.7;
}

.task-title {
  font-weight: 500;
  margin-bottom: 10px;
}

.task-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.task-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
}

.column-pagination {
  margin-top: 15px;
  padding: 10px 0;
  display: flex;
  justify-content: center;
  border-top: 1px solid #f0f0f0;
}

.column-pagination :deep(.el-pagination) {
  justify-content: center;
}
</style>

